package com.travel.servlet;

import java.io.IOException;
import java.util.Set;

import javax.servlet.ServletException;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import org.json.JSONArray;
import org.json.JSONObject;

import BUCF.recommendSpots;
import BUCF.similarityUsers;
import BUCF.step;
import BUCF.userStep;
import BUCF.user_sim;

public class UserRelatedRecommend extends HttpServlet {

	private static final long serialVersionUID = 8644845520417185455L;

	@Override
	protected void doGet(HttpServletRequest request, HttpServletResponse response)
			throws ServletException, IOException {
		String userId = "17608579";
		Set<user_sim> users = new similarityUsers(userId, 10).getUsers();

		Set<step> steps = new userStep(userId).getUserStep();

		Set<String> spots = new recommendSpots(userId, 10).getSpots();

		// 通过json传递数据到前台
		JSONArray jsonArrayUsers = new JSONArray();// 最外层json
		JSONArray jsonArraySteps = new JSONArray();// 最外层json
		JSONArray jsonArraySpots = new JSONArray();// 最外层json

		java.text.DecimalFormat df = new java.text.DecimalFormat("#.000");

		for (String spotName : spots) {
			JSONObject jo = new JSONObject();
			try {
				jo.put("spotName", spotName);
			} catch (Exception e) {
				e.printStackTrace();
			}
			jsonArraySpots.put(jo);
		}

		for (user_sim u : users) {
			JSONObject jo = new JSONObject();
			try {
				jo.put("userName", u.getUser());
				jo.put("userSim", df.format(u.getSim()));// 保留三位小数
			} catch (Exception e) {
				e.printStackTrace();
			}

			jsonArrayUsers.put(jo);
		}

		for (step s : steps) {
			JSONObject jo = new JSONObject();
			try {
				jo.put("spotName", s.getSpot());// 获取历史浏览过的景点名称
				jo.put("travelTime", s.getTime());//
			} catch (Exception e) {
				e.printStackTrace();
			}
			jsonArraySteps.put(jo);
		}
		JSONObject jo = new JSONObject();

		try {
			jo.put("currUserId", "17608579");// 获取历史浏览过的景点名称
			jo.put("currUserName", "Wayne颖");//
			jo.put("historySteps", jsonArraySteps);//
			jo.put("relatedUsers", jsonArrayUsers);//
			jo.put("recommendedSpots", jsonArraySpots);//
		} catch (Exception e) {
			e.printStackTrace();
		}
		response.setCharacterEncoding("utf-8");

		// response.getWriter().write(jo.toString().getBytes("UTF-8"));
		response.getOutputStream().write(jo.toString().getBytes("UTF-8"));
	}

	@Override
	protected void doPost(HttpServletRequest request, HttpServletResponse response)
			throws ServletException, IOException {
		doGet(request, response);
	}
}
